import React, {Component} from 'react';
import {Form, Input, Button, Tag, message, Popconfirm} from 'antd';
import {UserOutlined, LockOutlined} from '@ant-design/icons';
import {FormInstance} from 'antd';
import {httpClient} from '../utils/request';
import {IAppInfo} from './IFormProps';
import {getDebounceCallbackFn} from '../utils/common';
import {Cookies} from 'react-cookie';

const cookie = new Cookies();

class AppInfoForm extends Component<IAppInfo, never> {


    // 当前组件的实例
    formInstance = React.createRef<FormInstance>();

    /**
     * 真实获取应用信息的方法
     */
    doGetAppInfo: (...args: any) => void = getDebounceCallbackFn(async (form) => {
        const {appId, appSecret} = form.getFieldsValue();
        const content = await httpClient.post({
            url: '/auth/getAppAccessToken',
            tokenType: '',
            params: {
                receive_type: 'input'
            },
            data: {
                app_id: appId,
                app_secret: appSecret,
            }
        });
        const {data} = (content as any)['data'];
        if (data.code === 0) {
            message.success('获取应用凭证成功！已禁止按钮，请勿重复获取');
            cookie.set('tenant_token', data.tenant_access_token, {expires: data.expires});
            cookie.set('app_token', data.tenant_access_token, {expires: data.expires});
        }
    }, 1000);

    doClearAppInfo: (...args: any) => void = getDebounceCallbackFn(async (form) => {
        form.setFieldsValue(
            {
                appId: this.props.appId,
                appSecret: this.props.appSecret,
            },
        );
        const content = await httpClient.delete({
            url: '/auth/clearAppInfo',
            tokenType: '',
        });
        console.log(content);
        const {data} = (content as any);
        if (data.code === 0) {
            message.success('本地与客户端信息清除成功！');
        }
    }, 500);


    async handleClick(): Promise<void> {
        const form = this.formInstance.current;
        if (form !== null) {
            // 实际请求
            this.doGetAppInfo(form);
        }
    }

    async handleClear(): Promise<void> {
        const form = this.formInstance.current;
        if (form !== null) {
            this.doClearAppInfo(form);
        }
    }

    /**
     * 渲染组件
     */
    render(): React.ReactNode {
        return (
            <div>
                <Tag color="magenta">先确认信息</Tag>
                <Form layout="inline"
                      ref={this.formInstance}
                      initialValues={
                          {
                              appId: this.props.appId,
                              appSecret: this.props.appSecret
                          }
                      }
                >

                    <Form.Item
                        name="appId"
                        rules={[{required: true, message: '请输入app id'}]}
                    >
                        <Input prefix={<UserOutlined className="site-form-item-icon"/>} placeholder="app id"/>
                    </Form.Item>
                    <Form.Item
                        name="appSecret"
                        rules={[{required: true, message: '请输入app secret'}]}
                    >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon"/>}
                            type="password"
                            placeholder="app secret"
                        />
                    </Form.Item>
                    <Form.Item shouldUpdate={(prevValues, curValues) => prevValues.additional !== curValues.additional}>
                        {() => (
                            <Button
                                type="primary"
                                onClick={this.handleClick.bind(this)}
                            >
                                确认信息
                            </Button>
                        )}
                    </Form.Item>
                    <Form.Item shouldUpdate={(prevValues, curValues) => prevValues.additional !== curValues.additional}>
                        {() => (
                            <Popconfirm
                                title="此操作将会同步清空服务端存储的信息？"
                                onConfirm={this.handleClear.bind(this)}
                                okText="确认"
                                cancelText="取消"
                            >
                                <Button danger>
                                    清空信息
                                </Button>
                            </Popconfirm>
                        )}
                    </Form.Item>
                </Form>
            </div>
        );
    }
}

export default AppInfoForm;
